#include <stdio.h>
#include <stdlib.h>
#include "linsyst.h"


syst * createsyst(int size){
	syst * lsys;

	lsys = (syst *) malloc(sizeof(syst));
	if(lsys == NULL) return NULL;

	lsys->matA = (float *) malloc(sizeof(float) * size * size);
	if(lsys->matA == NULL){
		free(lsys);
		return NULL;
	}

	lsys->vetB = (float *) malloc(sizeof(float) * size);
	if(lsys->vetB == NULL){
		free(lsys->matA);
		free(lsys);
		return NULL;
	}

	lsys->vetX0 = (float *) malloc(sizeof(float) * size);
	if(lsys->vetX0 == NULL){
		free(lsys->vetB);
		free(lsys->matA);
		free(lsys);
		return NULL;
	}

	lsys->vetX1 = (float *) malloc(sizeof(float) * size);
	if(lsys->vetX1 == NULL){
		free(lsys->vetX0);
		free(lsys->vetB);
		free(lsys->matA);
		free(lsys);
		return NULL;
	}

	lsys->size = size;	

	return lsys;
}

void destroysyst(syst * lsys){
	if(lsys != NULL){
		free(lsys->vetX1);
		free(lsys->vetX0);
		free(lsys->vetB);
		free(lsys->matA);
		free(lsys);
	}
}

syst * loadsyst(const char * file){
	FILE * fp;
	int iIn;
	float fIn;
	int it, tam, ferro = 0;
	syst * lsys; 


	fp = fopen(file, "r");
	if(fp == NULL) {
		perror("Erro open file");
		return NULL;
	}


	fscanf(fp, "%d ", &iIn);
	lsys = createsyst(iIn);
	if(lsys == NULL) {
		perror("Erro malloc");
		return NULL;
	}

	/* Leitura dos parametros */
	fscanf(fp, "%d ", &iIn);
	lsys->ref = iIn;

	fscanf(fp, "%f ", &fIn);
	lsys->prec = fIn;

	fscanf(fp, "%d ", &iIn);
	lsys->max_it = iIn;


	/* Leitura da matriz A */
	tam = lsys->size * lsys->size;
	for(it = 0; it < tam; it++)
		if(fscanf(fp, "%f ", lsys->matA + it) != 1)
			ferro = 1;

	if(ferro){
		perror("Erro load matriz A");
		destroysyst(lsys);
		return NULL;
	}

	/* Leitura do vetor B */
	tam = lsys->size;
	for(it = 0; it < tam; it++)
		if(fscanf(fp, "%f ", lsys->vetB + it) != 1)
			ferro = 1;

	if(ferro){
		perror("Erro load vetor B");
		destroysyst(lsys);
		return NULL;
	}

	it = lsys->ref;
	it *= lsys->size;
	it += lsys->ref;
	lsys->el_digref = lsys->matA[it];

	return lsys;
}


